import type { I18n as VueI18n, Locale } from 'vue-i18n';
import { createI18n as createVueI18n } from 'vue-i18n';
import { DEFAULT_LANGUAGE } from '@/common/utils/constants';

function loadLanguage(prefix: string) {
  const lang = import.meta.glob('@/common/locales/*.y(a)?ml', {
    eager: true,
    import: 'default',
  }) as Record<string, any>;
  const re = new RegExp(`/${prefix}\.`, 'i');
  const key = Object.keys(lang).find(item => item.match(re)) as string;

  return lang[key];
}

export type I18n = VueI18n<NonNullable<unknown>, NonNullable<unknown>, NonNullable<unknown>, Locale, false>;

export function createI18n(language = DEFAULT_LANGUAGE) {
  return createVueI18n({
    legacy: false,
    allowComposition: true,
    locale: language,
    fallbackLocale: {
      'en-US': [DEFAULT_LANGUAGE],
    },
    messages: {
      'zh-CN': {
        ...loadLanguage('zh-CN'),
      },
      'en-US': {
        ...loadLanguage('en-US'),
      },
    },
  }) as I18n;
}
